﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using CivilleWP7.Views.Controls;
using CivilleWP7.CivilleDataServiceReference;
using System.Collections.ObjectModel;
using CivilleWP7.Civille.Source;
using System.Data.Services.Client;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Shell;
using SL.Phone.Federation.Utilities;

namespace CivilleWP7.Views.Pages
{
    public partial class FriendsMorePage : PhoneApplicationPage
    {
        private string search;
        private bool IsLightTheme;
        public FriendsMorePage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(FriendsMorePage_Loaded);
            SearchTextBox.KeyDown += new KeyEventHandler(SearchTextBox_KeyDown);
            setBackground();
        }
        void checkThemeColor()
        {
            var visibility = (Visibility)Application.Current.Resources["PhoneLightThemeVisibility"];
            if (visibility == Visibility.Visible)
                IsLightTheme = true;
            else
                IsLightTheme = false;
        }
        void setBackground()
        {
            checkThemeColor();
            ImageBrush myBrush = new ImageBrush();
            if(IsLightTheme)
                myBrush.ImageSource=new BitmapImage(new Uri("/Resources/Images/Backgroundwhite.jpg",UriKind.Relative));
            else
                myBrush.ImageSource = new BitmapImage(new Uri("/Resources/Images/Background.jpg",UriKind.Relative));
            ContentPanel.Background=myBrush;
        }
        private void NewSearch()
        {
            FriendsListBox.Items.Clear();
            search = SearchTextBox.Text;
            PageTitle.Text = "Results for "+search;
            PopulateFriendListOnSearch();
        }

        void SearchTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                NewSearch();
                this.Focus();
            }
        }
        private void Image_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NewSearch();
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            search = NavigationContext.QueryString["friend"];
            if (!search.Equals(""))
            {
                PageTitle.Text = "Results for "+search;
                PopulateFriendListOnSearch();
            }
        }
        private void PopulateFriendListOnSearch()
        {
            CivilleDataServiceConnector.SetFriendQueryParameters(search);
            CivilleDataServiceConnector.SearchFriendQuery.BeginExecute(OnSearchFriendQueryComplete, CivilleDataServiceConnector.SearchFriendQuery);
        }
        private void OnSearchFriendQueryComplete(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() =>
            {
                DataServiceQuery<CivilleUser> query = result.AsyncState as DataServiceQuery<CivilleUser>;
                foreach (CivilleUser user in query.EndExecute(result))
                {
                    FriendsControl friend = new FriendsControl();
                    friend.Width = FriendsListBox.ActualWidth;
                    if (user.Logo != null && !user.Logo.Equals(""))
                        friend.Picture.Source = new BitmapImage(new Uri(user.Logo, UriKind.Absolute));
                    friend.ID = user.ID;
                    friend.NameTextblock.Text = user.FirstName + " " + user.LastName;
                    friend.LevelTextBlock.Text = "Level: " + user.CurrentLevel;
                    FriendsListBox.Items.Add(friend);
                    users.Add(user);
                    friend.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(friend_Tap);
                }
            });
        }
        List<CivilleUser> users = new List<CivilleUser>();
        void friend_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            foreach (CivilleUser user in users)
            {
                if (user.ID == (sender as FriendsControl).ID)
                {
                    FriendPage.User = user;
                    NavigationService.Navigate(new Uri("/Views/Pages/FriendPage.xaml", UriKind.Relative));
                }
            }
        }
        void FriendsMorePage_Loaded(object sender, RoutedEventArgs e)
        {
            
        }
        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to log out?", "Log out", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                RequestSecurityTokenResponseStore _rstrStore = App.Current.Resources["rstrStore"] as RequestSecurityTokenResponseStore;
                _rstrStore.RequestSecurityTokenResponse = null;
                NavigationService.Navigate(new Uri("/Views/Pages/SelectAuthPage.xaml", UriKind.Relative));
            }
        }
    }
}
